package com.stylefeng.guns.modular.paiqian.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.modular.ActionLog.service.IActionLogService;
import com.stylefeng.guns.modular.info.service.ICarInfoService;
import com.stylefeng.guns.modular.manage.service.ICarMaService;
import com.stylefeng.guns.modular.system.model.ActionLog;
import com.stylefeng.guns.modular.system.model.CarInfo;
import com.stylefeng.guns.modular.system.model.CarMa;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import com.stylefeng.guns.modular.system.model.Car;
import com.stylefeng.guns.modular.paiqian.service.ICarService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 车辆派遣控制器
 *
 * @author fengshuonan
 * @Date 2018-08-23 10:53:49
 */
@Controller
@RequestMapping("/car")
public class CarController extends BaseController {

    private String PREFIX = "/paiqian/car/";

    @Autowired
    private ICarService carService;
    @Autowired
    private ICarInfoService carInfoService;
    @Autowired
    private IActionLogService actionLogService;
    @Autowired
    private ICarMaService carMaService;
    /**
     * 跳转到车辆派遣首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "car.html";
    }

    /**
     * 跳转到添加车辆派遣
     */
    @RequestMapping("/car_add")
    public String carAdd() {
        return PREFIX + "car_add.html";
    }

    /**
     * 跳转到修改车辆派遣
     */
    @RequestMapping("/car_update/{carId}")
    public String carUpdate(@PathVariable Integer carId, Model model) {
        Car car = carService.selectById(carId);
        DateFormat format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String gotime=format.format(car.getGotime());
        String cometime=format.format(car.getCometime());
        model.addAttribute("gotime",gotime);
        model.addAttribute("cometime",cometime);
        model.addAttribute("item",car);
        LogObjectHolder.me().set(car);
        return PREFIX + "car_edit.html";
    }
    /**
     * 跳转到details
     */
    @RequestMapping("/details/{carId}")
    public String details(@PathVariable Integer carId, Model model) {
        Car car = carService.selectById(carId);
        Date gotime=car.getGotime();
        Date cometime=car.getCometime();
        DateFormat d=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time=d.format(gotime);
        String btime=d.format(cometime);

        model.addAttribute("item",car);
        model.addAttribute("time",time);
        model.addAttribute("btime",btime);
        LogObjectHolder.me().set(car);
        return PREFIX + "details.html";
    }

    /**
     * 获取车辆派遣列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String unit,String number)
    {
        if(unit!=null||unit!=""||number!=null||number!="") {
        EntityWrapper<Car> wrapper = new EntityWrapper<Car>();
        wrapper.like("unit", unit);
        if(number!=null||number!=""){
            wrapper.like("number",number);
        }
        return carService.selectList(wrapper);
    }else{
        return carService.selectList(null);
    }
    }

    /**
     * 新增车辆派遣
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Car car) {

        EntityWrapper<CarInfo> wrapper =new EntityWrapper<CarInfo>();
        wrapper.and("plate_number='"+car.getNumber()+"'");

        CarInfo carinfo=new CarInfo();
        carinfo.setStatus(3);
        CarMa carMa = new CarMa();
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = dateFormat.format(date);
        carMa.setOrTime(strDate);
        carMa.setStatus(3);
        car.setStatus(3);
        EntityWrapper<CarMa> carMaWrapper =new EntityWrapper<CarMa>();
        carMaWrapper.and("plate_numbr='"+car.getNumber()+"'");
        carMaService.update(carMa,carMaWrapper);
        carInfoService.update(carinfo,wrapper);
        carService.insert(car);

        return SUCCESS_TIP;
    }

    /**
     * 删除车辆派遣
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer carId) {

        Car car=carService.selectById(carId);
        EntityWrapper<CarInfo> wrapper =new EntityWrapper<CarInfo>();
        wrapper.and("plate_number='"+car.getNumber()+"'");
        CarInfo carinfo=new CarInfo();
        carinfo.setStatus(0);
        CarMa carMa = new CarMa();
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = dateFormat.format(date);
        carMa.setOrTime(strDate);
        carMa.setStatus(1);
        EntityWrapper<CarMa> carMaWrapper =new EntityWrapper<CarMa>();
        carMaWrapper.and("plate_numbr='"+car.getNumber()+"'");
        carMaService.update(carMa,carMaWrapper);
        carInfoService.update(carinfo,wrapper);
        carService.deleteById(carId);
        return SUCCESS_TIP;
    }

    /**
     * 修改车辆派遣
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Car car) {

       Car carupdate= carService.selectById(car.getId());
       if(carupdate.getNumber().equals(car.getNumber())){
           carService.updateById(car);
       }else{
           EntityWrapper<CarInfo> wrapperOne =new EntityWrapper<CarInfo>();
           wrapperOne.and("plate_number='"+carupdate.getNumber()+"'");
           CarInfo carinfoOne=new CarInfo();
          carinfoOne.setStatus(0);
          carInfoService.update(carinfoOne,wrapperOne);

           EntityWrapper<CarMa> wrapperMa =new EntityWrapper<CarMa>();
           wrapperMa.and("plate_numbr='"+carupdate.getNumber()+"'");
           CarMa carMa=new CarMa();
           carMa.setStatus(1);
           carMaService.update(carMa,wrapperMa);

          EntityWrapper<CarInfo> wrapperTwo =new EntityWrapper<CarInfo>();
           wrapperTwo.and("plate_number='"+car.getNumber()+"'");
           CarInfo carinfoTwo=new CarInfo();
                   carinfoTwo.setStatus(3);
               carInfoService.update(carinfoTwo,wrapperTwo);

           EntityWrapper<CarMa> wrapperMaTow =new EntityWrapper<CarMa>();
           wrapperMaTow.and("plate_numbr='"+car.getNumber()+"'");
           CarMa carMaTow=new CarMa();
           Date date = new Date();
           SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
           String strDate1 = dateFormat.format(date);
           carMaTow.setOrTime(strDate1);
           carMaTow.setStatus(3);
           carMaService.update(carMaTow,wrapperMaTow);
                   carService.updateById(car);
       }
        return SUCCESS_TIP;
    }

    /**
     * 车辆派遣详情
     */
    @RequestMapping(value = "/detail/{carId}")
    @ResponseBody
    public Object detail(@PathVariable("carId") Integer carId) {
        return carService.selectById(carId);
    }

    /**
     * 车辆审核
     */
    @RequestMapping(value = "/pass")
    @ResponseBody
    public Object pass(@RequestParam Integer carId) {
        Car car=new Car();
        car.setId(carId);
        try{
            Car carStatus=carService.selectById(car);
            if(carStatus.getStatus()==1){
                EntityWrapper<CarInfo> wrapper =new EntityWrapper<CarInfo>();
                wrapper.and("plate_number='"+carStatus.getNumber()+"'");
                CarInfo carinfo=new CarInfo();
                carinfo.setStatus(1);
                carInfoService.update(carinfo,wrapper);
                car.setStatus(0);
                carService.updateById(car);
                return SUCCESS_TIP;
            }else{
                EntityWrapper<CarInfo> wrapperOne =new EntityWrapper<CarInfo>();
                wrapperOne.and("plate_number='"+carStatus.getNumber()+"'");
                CarInfo carinfoOne=new CarInfo();
                carinfoOne.setStatus(0);
                carInfoService.update(carinfoOne,wrapperOne);
                car.setStatus(1);
                carService.updateById(car);
                return SUCCESS_TIP;
            }
        }catch (Exception e){
            return ERROR;
        }
    }
    /**
     * 车牌号查询
     */
    @RequestMapping(value = "/status")
    @ResponseBody
    public Object status() {
        Wrapper<CarInfo> wrapper=new EntityWrapper<CarInfo>();
        wrapper.and("status = 0");
        List<CarInfo> carInfo =carInfoService.selectList(wrapper);
        return carInfo;
    }

    /**
     * 打印日志
     */
    @RequestMapping("/download")
    @ResponseBody
    public void download(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("信息表");

        List<Car> classmateList = carService.selectList(null);

        String fileName = "车辆派遣"  + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据

        int rowNum = 1;

        String[] headers = { "编号", "出车时间", "回车时间", "用车单位","车号","用（带）车人","联系电话","批准人","驾驶人","行车路线","事由"};
        //headers表示excel表中第一行的表头

        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头

        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Car actionLog : classmateList) {
            DateFormat format =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String gotime=format.format(actionLog.getGotime());
            String cometime=format.format(actionLog.getCometime());
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(actionLog.getId());
            row1.createCell(1).setCellValue(cometime);
            row1.createCell(2).setCellValue(gotime);
            row1.createCell(3).setCellValue(actionLog.getUnit());
            row1.createCell(4).setCellValue(actionLog.getNumber());
            row1.createCell(5).setCellValue(actionLog.getPeople());
            row1.createCell(6).setCellValue(actionLog.getPhone());
            row1.createCell(7).setCellValue(actionLog.getApproval());
            row1.createCell(8).setCellValue(actionLog.getJiashi());
            row1.createCell(9).setCellValue(actionLog.getRoad());
            row1.createCell(10).setCellValue(actionLog.getReason());
            rowNum++;
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }


    @RequestMapping(value = "/selectList")
    @ResponseBody
    public Object selectList() {
        Wrapper<ActionLog> wrapper=new EntityWrapper<ActionLog>();
        Date data =new Date();
        DateFormat format =new SimpleDateFormat("yyyy-MM-dd");
         String time=format.format(data);
        wrapper.like("io_time",time).and("log_type='异常通行记录'");
        int carInfo =actionLogService.selectCount(wrapper);
        Wrapper<ActionLog> wrapper1=new EntityWrapper<ActionLog>();
        wrapper1.like("io_time",time).and("log_type='正常通行记录'");
        int carInfo1 =actionLogService.selectCount(wrapper1);
       List a=new ArrayList();
       a.add(carInfo);
       a.add(carInfo1);
        return a;
    }
}
